<?php

/**
 * This is the model class for table "{{video}}".
 *
 * The followings are the available columns in table '{{video}}':
 * @property integer $id
 * @property string $module
 * @property integer $module_id
 * @property integer $is_default
 * @property string $url
 * @property string $embed_html
 * @property string $caption
 * @property string $tags
 * @property integer $width
 * @property integer $height
 * @property integer $duration
 * @property string $image_url
 * @property integer $image_width
 * @property integer $image_height
 * @property integer $image_size
 * @property string $image_caption
 * @property integer $total_view
 * @property integer $total_like
 * @property integer $total_shortlist
 * @property integer $status_code
 * @property string $create_timezone
 * @property string $create_timestamp
 * @property string $create_datetime
 * @property string $create_date
 * @property string $create_time
 * @property integer $create_by
 * @property string $update_timezone
 * @property string $update_timestamp
 * @property string $update_datetime
 * @property string $update_date
 * @property string $update_time
 * @property integer $update_by
 */
class Video extends ActiveRecord {
    
    public $moduleId_;
    public $module_;
    public $file_;
    public $url_;
    
    public $default_;
    public $caption_;
    public $tags_;
    
    private $_oembed;
    
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Video the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{video}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
           array('moduleId_, module_, caption_', 'filter', 'filter'=>'trim'),
           //array('caption_','filter','filter'=>array($obj=new CHtmlPurifier(),'purify')),
           array('url_', 'url', 'defaultScheme'=>'http'),
            
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            // must included
            'creator' => array(self::BELONGS_TO, 'User', 'create_by'),
            'editor' => array(self::BELONGS_TO, 'User', 'update_by'),
            
            
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'url_'=>Lang::t('video.lbl.url'),
            'caption_'=>Lang::t('video.lbl.caption'),
        );
    }

        /**
     * scopes
     */   
    public function scopes() {
        $t = $this->getTableAlias(false);
        return array(
            'primary'=>array(
                'condition' => implode(' AND ',array(
                    $t.'.is_default=1',
                )),
            ),
            'published'=>array(
                'condition' => $t.'.status_code = :activeStatus'.$t,
                'params' => array(
                    ':activeStatus'.$t => Option::STATUS_ACTIVE,
                ),
            ),
            'ordered'=>array(
                'order'=>implode(',',array(
                    $t.'.is_default DESC',
                    $t.'.create_time DESC',
                )),
            ),
            'accessible'=>array(
                'condition' => $t.'.status_code <> :deletedStatus'.$t,
                'params' => array(
                    ':deletedStatus'.$t => Option::STATUS_DELETED,
                ),
            ),
        );
    }

    public function module($module = null) {
        $t = $this->getTableAlias(false);
        $this->getDbCriteria()->mergeWith(array(
            'condition' => $t.'.module = :module'.$t,
            'params' => array(
                ':module'.$t => strtolower($module),
            ),
        ));
        return $this;
    }

    public function moduleId($id = null) {
        $t = $this->getTableAlias(false);
        $this->getDbCriteria()->mergeWith(array(
            'condition' => $t . '.module_id = :moduleId'.$t,
            'params' => array(
                ':moduleId'.$t => (int)$id,
            ),
        ));
        return $this;
    }
    
    public function setDefault(&$module, &$moduleId, $id=null){
        $model=$this->primary()->accessible()->module($module)->moduleId($moduleId)->find();
        if($model && $id){
            $newDefault=$this->accessible()->module($module)->moduleId($moduleId)->findByPk((int)$id);
            if($newDefault->saveAttributes(array('is_default'=>true))){
                $model->saveAttributes(array('is_default'=>false));
            }
        }elseif(empty($model) && empty($id)){
            $model=$this->accessible()->module($module)->moduleId($moduleId)->find();
            if(!empty($model))
                $model->saveAttributes(array('is_default'=>true));
        }
    }
    
    public function getUploadPath() {
        $uploadPath = Yii::app()->params['mediaPath'];
        $format = 'Y/M/d';
        switch ($this->scenario) {
            case 'insert':
            case 'userCreate':
            case 'userUpdate':
            case 'adminCreate':
            case 'adminUpdate':
                return implode('/', array_filter(array(
                    str_replace(Yii::app()->params['mediaDomain'], Yii::app()->params['relativeMediaPath'], $uploadPath),
                    date($format),
                )));
                break;
            case 'delete':
            case 'userDelete':
            case 'adminDelete':
                return implode('/', array_filter(array(
                    str_replace(Yii::app()->params['mediaDomain'], Yii::app()->params['relativeMediaPath'], $uploadPath),
                    date($format, strtotime($this->create_time)),
                )));
                break;
            
            case 'update':
            default:
                return implode('/', array_filter(array(
                    $uploadPath,
                    date($format, strtotime($this->create_time)),
                )));
                break;
        }//end switch
    }
    
    protected function beforeSave() {
        if (parent::beforeSave()) {
            if ($this->isNewRecord) {
                $this->module_id = $this->moduleId_;
                $this->module = strtolower($this->module_);
                $this->url=$this->url_;
                $this->caption=$this->caption_;
                $this->status_code =Option::STATUS_ACTIVE;
                $this->setCreateDateTime();
            } else {
                $this->setUpdateDateTime();
            }
            return true;
        }
        else
            return false;
    }

    protected function afterSave() {
        parent::afterSave();

        $this->saveLog();
    }
    
    public function addRecord(){
        foreach($this->file_ as $key=>$value){
            if(!isset($value['url']) || empty($value['url'])) continue;
            
            $model=new $this;
            $model->moduleId_=$this->moduleId_;
            $model->module_=$this->module_;
            if(isset($value['url'])) $model->url_=$value['url'];
            if(isset($value['caption'])) $model->caption_=$value['caption'];
            
            $data = Yii::app()->oembed->extract($value['url']);
            if(empty($data)) continue;
            
            if(!isset($value['caption'])) $model->caption_=$data->title;
            
            $model->html = $data->media->html;
            $model->width = $data->media->width;
            $model->height = $data->media->height;
            $model->duration = $data->media->duration;
            
            $keywords = array();
            foreach($data->keywords as $keyword){
                $keywords[] = $keyword->name;
            }
            $model->tags = implode(',', $keywords);
            
            $image = $data->images[0];
            $model->image_url = $image->url;
            $model->image_width = $image->width;
            $model->image_height = $image->height;
            $model->image_size = $image->size;
            $model->image_caption = $image->caption;
            
            if(!$model->save(true))
                $this->addErrors($model->getErrors());
        }
        $this->setDefault($this->module_, $this->moduleId_);
    }
    
    public function updateRecord(){
        foreach($this->file_ as $id=>$value){
            
            if(isset($value['url'])) $this->url_=$value['url'];
            if(isset($value['caption']))$this->caption_=$value['caption'];

            if($this->validate(array('url_', 'caption_'))){                
                
                $params['url'] = $this->url_;
                $params['caption'] = $this->caption_;
                
                $data = Yii::app()->oembed->extract($this->url_);
                if(!empty($data)){
                    
                    if(!isset($value['caption'])) $params['caption']=$data->title;
                    $params['html'] = $data->media->html;
                    $params['width'] = $data->media->width;
                    $params['height'] = $data->media->height;
                    $params['duration'] = $data->media->duration;

                    $keywords = array();
                    foreach($data->keywords as $keyword){
                        $keywords[] = $keyword->name;
                    }
                    $params['tags'] = implode(',', $keywords);

                    $image = $data->images[0];
                    $params['image_url'] = $image->url;
                    $params['image_width'] = $image->width;
                    $params['image_height'] = $image->height;
                    $params['image_size'] = $image->size;
                    $params['image_caption'] = $image->caption;
                }
                
                return $this->updateByPk($id, $params);
                //success
            }else{
                //$this->addError('error', Lang::t('video.error.update.fail', array('{id}'=>$id)));
                //print_r($this->getErrors());
            }
        }
    }
    
    public function deleteRecord(){
        $this->status_code=Option::STATUS_DELETED;
        return $this->save(true);
    }
    
    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('module_id', $this->module_id);
        $criteria->compare('module', $this->module, true);
        $criteria->compare('is_default', $this->is_default);
        $criteria->compare('caption', $this->caption, true);
        $criteria->compare('url', $this->url, true);
        $criteria->compare('total_view', $this->total_view);
        $criteria->compare('total_like', $this->total_like);
        $criteria->compare('total_bookmark', $this->total_bookmark);
        $criteria->compare('status_code', $this->status_code);
        $criteria->compare('create_time', $this->create_time, true);
        $criteria->compare('create_by', $this->create_by);
        $criteria->compare('update_time', $this->update_time, true);
        $criteria->compare('update_by', $this->update_by);

        return new ActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function getIsDefault(){
        return !empty($this->is_default);
    }

    public function getHasThumbnail(){
        return !empty($this->image_url);
    }
    
    public function getThumbnail($value=null) {
        return $this->image_url;
    }
    
    public function getThumbnailWidth() {
        return $this->image_width;
    }
    
    public function getThumbnailHeight() {
        return $this->image_height;
    }
    
    public function getThumbnailSize(){
        return $this->image_size;
    }
    
    public function getHasHtml(){
        return !empty($this->html);
    }
    
    public function getEmbedHtml(){
        $options = array();
        if(isset($this->defaultWidth))
            $options['width="'.$this->width.'"']='width="'.$this->defaultWidth.'"';
        
        if(isset($this->defaultHeight))
            $options['height="'.$this->height.'"']='height="'.$this->defaultHeight.'"';
        
        return strtr($this->html, $options);
    }    
    
    public function getFileName() {
        return CHtml::encode($this->name);
    }
    
    public function getFileUrl(){
        return CHtml::encode($this->url);
    }    

    public function getFileCaption() {
        return CHtml::encode($this->caption);
    }
    
    public function getFileType() {
        return CHtml::encode($this->type);
    }

    public function getFileSize() {
        return CHtml::encode((double)$this->size);
    }
    
    public function getTags() {
        return CHtml::encode($this->tags);
    }
    
    
    /*
    // OEmbed APIs
    public function loadOEmbed($url=null){
        if(empty($url) && in_array($this->scenario, array('update', 'userUpdate', 'adminUpdate'))) 
                $url=$this->url;
        
        if(empty($this->_oembed)){
            $option=array();
            if(!empty($this->defaultWidth)) $option['width']=$this->defaultWidth;
            if(!empty($this->defaultHeight)) $option['height']=$this->defaultHeight;
            
            $this->_oembed=OEmbed::getResponse($url, 'video', $option);
            if(empty($this->_oembed)) return array();
        }
        return $this->_oembed;
    }
    
    public function getHasOEmbed($url=null){
        $this->loadOEmbed($url);
        return !empty($this->_oembed);
    }
    
    private function getOEmbedValue($attribute, $default=null){
        return isset($this->loadOEmbed()->$attribute)?$this->loadOEmbed()->$attribute:$default;
    }
    
    public function getOEmbedData(){
        return $this->loadOEmbed();
    }
    
    public function getTitle(){
        return $this->getOEmbedValue('title');
    }
    
    public function getEmbedHtml(){
        return $this->getOEmbedValue('html', $this->defaultImage);
    }
    
    public function getThumbnail($value=null){
        return $this->getOEmbedValue('thumbnail_url', $this->defaultImage);
    }
    
    public function getWidth(){
        return $this->getOEmbedValue('width');
    }
    
    public function getHeight(){
        return $this->getOEmbedValue('height');
    }
    
    public function getDescription(){
        return $this->getOEmbedValue('description');
    }
    
    public function getDuration(){
        return $this->getOEmbedValue('duration');
    }
    
    public function getAuthor(){
        return $this->getOEmbedValue('author_name');
    }
    
    public function getSource(){
        return $this->getOEmbedValue('provider_name');
    }
    // end OEmbed
    */
    
}